package controllers

import (
	"../../../deps/lessgo/pagelet"
	"../../../deps/lessgo/pass"
	"../../../deps/lessgo/utils"
	"../../store"
	"../models/session"
	"io"
	"net/http"
	"strings"
)

type User struct {
	*pagelet.Controller
}

func (c User) LoginAction() {
	c.ViewData["continue"] = c.Params.Get("continue")
	if c.Params.Get("persistent") == "1" {
		c.ViewData["persistentChecked"] = "checked"
	}
}

func (c User) LoginAuthAction() {

	c.AutoRender = false

	var rsp struct {
		ResponseJson
		Data struct {
			Continue    string `json:"continue"`
			AccessToken string `json:"access_token_keeper"`
		} `json:"data"`
	}
	rsp.ApiVersion = apiVersion
	rsp.Status = 400
	rsp.Message = "Bad Request"
	rsp.Data.Continue = "/keeper"

	defer func() {
		if rspj, err := utils.JsonEncode(rsp); err == nil {
			io.WriteString(c.Response.Out, rspj)
		}
	}()

	if c.Params.Get("uname") == "" || c.Params.Get("passwd") == "" {
		return
	}

	uname := strings.ToLower(c.Params.Get("uname"))
	node, err := store.NodeGet("/sys/ids/" + uname)
	if err != nil {
		return
	}
	if len(node.C) < 10 {
		return
	}

	if !pass.Check(c.Params.Get("passwd"), node.C) {
		rsp.Message = "Username or Password can not match"
		return
	}

	rsp.Data.AccessToken = utils.StringNewRand36(24)

	addr := "127.0.0.1"
	if addridx := strings.Index(c.Request.RemoteAddr, ":"); addridx > 0 {
		addr = c.Request.RemoteAddr[:addridx]
	}

	sess := session.Session{
		Uname:       uname,
		RemoteAddr:  addr,
		AccessToken: rsp.Data.AccessToken,
	}
	session.Set(sess)

	rsp.Status = 200
	rsp.Message = ""
}

func (c User) SignOutAction() {

	c.ViewData["continue"] = "/keeper"

	session.Del(c.Request)

	if len(c.Params.Get("continue")) > 0 {
		c.ViewData["continue"] = c.Params.Get("continue")
	}

	ck := &http.Cookie{
		Name:     "access_token_keeper",
		Value:    "",
		Path:     "/",
		HttpOnly: true,
		MaxAge:   -1,
	}
	http.SetCookie(c.Response.Out, ck)
}
